import { ref } from 'vue'

export const useDefer = (maxFrameCount: number) => {
  const frameCount = ref<number>(0)

  const refreshFrameCount = () => {
    requestAnimationFrame(() => {
      frameCount.value++

      if (frameCount.value < maxFrameCount) {
        refreshFrameCount()
      }
    })
  }

  refreshFrameCount()

  const defer = (showInFrameCount: number) => {
    return frameCount.value >= showInFrameCount
  }

  return {
    refreshFrameCount,
    defer
  }
}

export default function (maxFrameCount: number) {
  return {
    data() {
      return {
        frameCount: 0
      }
    },
    mounted() {
      const refreshFrameCount = () => {
        requestAnimationFrame(() => {
          this.frameCount++

          if (this.frameCount < maxFrameCount) {
            refreshFrameCount()
          }
        })
      }

      refreshFrameCount()
    },
    methods: {
      defer(showInFrameCount: number) {
        return this.frameCount >= showInFrameCount
      }
    }
  }
}
